﻿using System;
using System.Text.RegularExpressions;
using Close2Poco;
using NUnit.Framework;

namespace Close2Poco.Tests
{
    /// <summary>
    /// Tests the generation of our XML mapping file by ensuring we generate the mapping we expect
    /// </summary>
    [TestFixture]
    public class TestMapping
    {
        [Test]
        public void Go()
        {
            MappingGenerator g = new MappingGenerator();  // will generate the mapping XML for all entities that it can find

            #region expectedXML = ...
            string expectedXML =
@"<?xml version=""1.0"" encoding=""utf-8""?>
   <!-- This file is autogenerated by Close2Poco
The XSD is downloaded from here:http://msdn2.microsoft.com/en-us/library/bb386907.aspx
       The attributes are described here: http://msdn2.microsoft.com/en-us/library/bb425822.aspx -->
<Database xmlns=""http://schemas.microsoft.com/linqtosql/mapping/2007""            
            xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
            xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
            Name=""DummyDBName"">

<Table Name=""Customer"">
      <Type Name=""Close2Poco.Tests.TestEntities.Customer"">
        <Column Member=""CustomerID"" IsPrimaryKey=""true"" DbType=""NChar(5)"" />
        <Column Member=""CompanyName""  DbType=""NVarChar(40)"" />
        <Column Member=""Contact"" Name=""ContactName"" DbType=""NVarChar(30)""  />
        <Column Member=""City"" DbType=""NVarChar(15)"" />
        <Association Name=""TODO"" Member=""Orders"" Storage=""_orders"" OtherKey=""CustomerID""  />
     </Type>
</Table> 

<Table Name=""Order"">
      <Type Name=""Close2Poco.Tests.TestEntities.Order"">
        <Column Member=""OrderID"" IsPrimaryKey=""true"" IsDbGenerated=""true"" />
        <Column Member=""OrderDate""  />
        <Column Member=""CustomerID""  />
        <Association Name=""TODO"" Member=""Customer"" Storage=""_customer"" ThisKey=""CustomerID"" />
    </Type>
</Table>

</Database>";
            #endregion

            expectedXML = NormalizeWhitespace(expectedXML);
            string actualXML = NormalizeWhitespace(g.Xml);

            Console.Write(g.Xml);
            Assert.AreEqual(expectedXML, actualXML);
        }

        string NormalizeWhitespace(string xml)
        {
            return _findSpaces.Replace(
                    _findTabs.Replace(
                        _findNewlines.Replace(xml, Environment.NewLine), 
                    @" "), 
                " ");
        }

        static readonly Regex _findSpaces = new Regex(" +");          
        static readonly Regex _findTabs = new Regex(@"(\t\s*)+");          
        static readonly Regex _findNewlines = new Regex(@"(\s*\r\n\s*)+");  
        
    }
    
    
}
